<template>
  <Header />
  <Menu />
  <Search />
    <div class="container-fluid novelcontainer">
      <div class="row random">
        搜索结果：{{ query }}
      </div>
      <div v-if="novels.length === 0" class="row noresult">
        啥都没有搜到 ~
      </div>
      <div v-for="novel in novels" :key="novel.novel_id" class="row g-0 novellist" @click="goToNovel(novel.novel_id)">
        <div class="col-4"><img :src="novel.novel_pic" alt="Novel Image" class="novel-image" /></div>
        <div class="col novel_list_info">
          <div class="row novel_name">{{ truncate2(novel.novel_name) }}</div>
          <div class="row novel_author">作者：{{ novel.novel_author.nickname }}</div>
          <div class="row">简介：{{ truncate(novel.novel_desc) }}</div>
        </div>
      </div>
    </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import axios from 'axios';
import Header from "@/components/Header.vue";
import Search from "@/views/index/Search.vue";
import Menu from "@/components/Menu.vue";
import router from "@/router/index.js";
import config from "../../../config/config.js";

const route = useRoute(); // 获取当前路由
const query = ref(route.params.query); // 获取搜索关键字
// 监听路由参数变化
watch(() => route.params.query, (newQuery) => {
  query.value = newQuery; // 更新搜索关键字
  fetchNovels(); // 重新获取搜索结果
});

const novels = ref([]); // 存储搜索结果

// 获取搜索结果
const fetchNovels = async () => {
  try {
    const response = await axios.get(`${config.apiUrl}/novel/search?novelName=${encodeURIComponent(query.value)}`);
    novels.value = response.data; // 存储搜索结果
  } catch (error) {
    console.error("Error fetching novels:", error); // 错误处理
  }
};

// 跳转到指定小说的函数
const goToNovel = (novelId) => {
  router.push(`/novel/${novelId}`); // 路由跳转
};

// 辅助函数
const truncate = (text) => {
  if (!text) return '';
  return text.length > 40 ? text.substring(0, 30) + '...' : text;
};

const truncate2 = (text) => {
  if (!text) return '';
  return text.length > 12 ? text.substring(0, 12) + '...' : text;
};

onMounted(fetchNovels); // 组件挂载时获取搜索结果
</script>

<style scoped>
.random{
  padding:10px 20px 0px 20px;
  font-weight: bold;
  font-size: 22px;
  letter-spacing: 2px;
}
.novellist{
  padding: 10px;
  cursor: pointer;
}
.novelcontainer{
  border-radius: 20px;
  width: 90%;
  padding: 10px;
  box-shadow:0px 0px 80px rgba(0, 0, 0, 0.06);
  margin-top: 10px;
}
.novellist img{
  width: 100px;
}
.novel_list_info{
  padding-left: 20px;
}
.novel_name{
  font-size: 17px;
  font-weight: bold;
}
.novel_author{
  padding: 4px 0px;
}
.noresult{
  padding: 20px;
}

</style>
